<template>
  <div class="app-container  bg-gray">
    <el-row class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <div>
              <el-button v-if="queryMatch(46)" type="success" class="bg-green" icon="el-icon-circle-plus" @click="toAdd">新增地区</el-button>
              <el-button type="primary" class="bg-green" icon="el-icon-download" @click="toExportData">导出数据</el-button>
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="id" label="ID" min-width="80" header-align="center" align="center" sortable />
            <el-table-column prop="name" label="服务范围" min-width="260"/>
            <el-table-column prop="admin_name" label="负责人" width="160" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row['admin_name'] || '--' }}
              </template>
            </el-table-column>
            <!--<el-table-column prop="tel" label="联系热线" width="200" header-align="center" align="center">
              <template slot-scope="scope">
                {{ scope.row['tel'] || '&#45;&#45;' }}
              </template>
            </el-table-column>-->
            <!--<el-table-column prop="created_at" label="创建时间" min-width="150"/>-->
            <el-table-column label="操作" min-width="200" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tooltip content="范围列表" placement="top">
                  <el-button size="small" type="primary" icon="el-icon-more" circle @click="toServiceArea(scope.row)"/>
                </el-tooltip>
                <el-button type="success" class="bg-green" size="small" icon="el-icon-edit" circle style="margin-left: 10px;" @click="toEdit(scope.row)"/>
                <el-button type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" :title="form.title" width="500px" class="dialog" center @close="resetDialog('form')">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="负责人" prop="admin_id">
          <!--不包含离职人员-->
          <el-select v-model="form.admin_id" :multiple-limit="2" placeholder="请选择负责人" class="select" clearable filterable multiple>
            <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id+''" />
          </el-select>
        </el-form-item>
        <!--<el-form-item label="联系热线" prop="tel">
          <el-input v-model="form.tel"/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { handleSortChange, handleSizeChange, handleCurrentChange } from '@/utils/table';
export default {
  data() {
    return {
      searchTerms: {
        searchValue: ''
      },

      // 弹出框相关数据
      dialogVisible: false,
      adminList: [],
      form: {
        id: '',
        cid: 0,
        name: '',
        admin_id: ''
        // tel: ''
      },
      rules: {
        name: [{ required: true, message: '请输入服务范围名称', trigger: 'change' }]
      },

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 280,

      // 表格相关参数
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: []
    }
  },
  created() {
    this.getData();
    this.getUsersList();
  },

  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange,
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'workorder/streetList'
      const data = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        cid: 0,
        search: this.searchTerms.searchValue
      }
      order.sortName && (data.sortName = order.sortName)
      order.sortOrder && (data.sortOrder = order.sortOrder)
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.tableLoading = false
      }).catch(e => {
        this.tableLoading = false
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取系统用户列表
     *  接口:'user/all-list'
     */
    getUsersList() {
      // const url = 'user/all-list'
      const url = 'user/admin-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.adminList = res.data['list'][0]['personnel'];
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    toServiceArea(row) {
      this.isShow = false
      this.$router.push({
        path: '/workOrder/serviceArea',
        query: { id: row.id }
      })
    },

    toDelete(row) {
      this.$confirm('此操作将删除该服务范围, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'workorder/delStreetId/' + row.id
        this.$store.dispatch('GetConnect', { url }).then(res => {
          this.$message.success(res.msg)
          this.getData()
        }).catch(e => {
          this.$message.error(e.msg);
        })
      })
    },

    toAdd() {
      this.form = {};
      this.dialogVisible = true;
      this.form.title = '添加服务范围';
      this.form.cid = 0
    },

    toEdit(row) {
      this.form = {}
      this.dialogVisible = true
      this.form = {
        id: row.id,
        cid: 0,
        name: row.name,
        admin_id: []
      }
      row.admin_id !== '' && (this.form['admin_id'] = row.admin_id.split(','))
      this.form.title = '编辑服务范围'
    },

    /**
     * 弹窗表单提交方法,通过判断有没有form_id执行添加或编辑操作
     * formName: form表单中ref的值,即表单名
     */
    submitDialog(formName) {
      this.$refs[formName].validate((valid) => { // 表单验证
        if (valid) {
          const url = this.form.id ? 'workorder/updateStreet' : 'workorder/addStreetInfo';
          const data = this.form;
          data.admin_id = data.admin_id.join(',');
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.dialogVisible = false;
            this.$message.success(res.msg);
            this.getData();
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员!')
          })
        } else {
          this.$message.error('提交失败,请检查必填项')
        }
      })
    },
    resetDialog(formName) {
      this.$refs[formName].resetFields()
    },

    // 导出数据
    toExportData() {
      this.downloadLoading = true;
      window.open(`${this.$store.getters.serverUrl}/admin/workorder/streetToExcel?token=${this.$store.getters.token}&mallId=${this.$store.getters.SaaSId}`)
      this.downloadLoading = false;
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../../styles/index.scss';
.box-1 {
  .header {
    @include flex-row(center, space-between);
    padding-bottom: 16px;
    flex-wrap: wrap;
    > div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
      width: 100%;
    }
    .search-input {
      width: 240px;
    }
    .do-btn {
      @extend .bg-green;
      margin-left: 6px;
    }
  }
}
.el-tag {
  cursor: pointer;
}
</style>
